package com.change.core.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.change.core.constant.RobotConstants;
import com.change.exception.BizException;
import com.change.exception.ResultStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.ZoneOffset;

/**
 * @author jhlz
 * @time 2022/8/19 21:07
 * @desc: JwtTokenAuthenticationInterceptor
 */
@Component
public class JwtTokenAuthenticationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取 token
        String token = request.getHeader("token");
        if (StrUtil.isBlank(token)) {
            throw new BizException(ResultStatus.Common.ROBOT_TOKEN_ISNULL);
        }
        // 解析 token：过期时间、生效时间、签发时间
        JWT jwt = JWTUtil.parseToken(token);
        long expiredTime = Long.valueOf(jwt.getPayload(JWTPayload.EXPIRES_AT).toString());
        /*String effectTime = jwt.getPayload(JWTPayload.NOT_BEFORE).toString();
        String issuedTime = jwt.getPayload(JWTPayload.ISSUED_AT).toString();*/
        LocalDateTime now = LocalDateTime.now();
        // 是否过期
        if (now.compareTo(
                LocalDateTime.ofEpochSecond(expiredTime, 0, ZoneOffset.UTC)) > 0) {
            throw new BizException(ResultStatus.Common.ROBOT_TOKEN_EXPIRED);
        }
        // 验证有效性
        boolean verify = JWTUtil.verify(token, RobotConstants.JWT_KEY.getBytes());
        if (verify) {
            return true;
        }
        return false;
    }

}
